package com.zmj.sy.mom.srv.aps.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zmj.sy.mom.srv.aps.bean.entity.mes.Part;
import com.zmj.sy.mom.srv.aps.bean.entity.mes.PartPallet;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.Position;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseIdReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseListResVo;
import com.zmj.sy.mom.srv.aps.bean.vo.position.*;
import com.zmj.sy.mom.srv.aps.bean.vo.workshop.EmbeddedStartModel;
import com.zmj.sy.mom.srv.aps.feign.WmsApiClient;
import com.zmj.sy.mom.srv.aps.mapper.PartMapper;
import com.zmj.sy.mom.srv.aps.mapper.PartPalletMapper;
import com.zmj.sy.mom.srv.aps.mapper.PositionMapper;
import com.zmj.sy.mom.srv.aps.mapper.StationMapper;
import com.zmj.sy.mom.srv.aps.utils.MkBeanUtils;
import com.zmj.sy.mom.srv.aps.utils.SyExceptionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Service
public class PositionService {

    private final PositionMapper positionMapper;


    private final PartPalletMapper partPalletMapper;
    private final PartService partService;
    private final WorkshopService workshopService;

    @Transactional
    public void add(PositionAddReqVo reqVo) {

        Integer count = positionMapper.lambdaQuery()
                .eq(Position::getMyCode, reqVo.getMyCode())
                .count();
        if (count > 0) {
            throw SyExceptionUtils.e("料位编码已存在");
        }

        Position position = MkBeanUtils.copyProperties(reqVo, Position.class);
        position.setType(1);
        position.setContainerType(1);
        positionMapper.insert(position);
    }


    public BaseListResVo<PositionListResVo> list(BaseIdReqVo reqVo) {
        LambdaQueryWrapper<Position> query = Wrappers.lambdaQuery();
        query.eq(Position::getStationId, reqVo.getId());
        List<Position> positionList = positionMapper.selectList(query);
        List<PositionListResVo> list = new ArrayList<>();
        for (Position position : positionList) {
            PositionListResVo vo = MkBeanUtils.copyProperties(position, PositionListResVo.class);
   /*         if (StringUtils.isEmpty(position.getStatus()) && !StringUtils.isEmpty(position.getLoadingCode())) {
                vo.setStatus(1);
            } else {
                vo.setStatus(2);
            }*/
            list.add(vo);
        }
        return BaseListResVo.of(list, PositionListResVo.class);
    }
//        BaseListResVo<PositionListResVo> resVo = BaseListResVo.of(positionPage, PositionListResVo.class);
//        for (PositionListResVo datum : resVo.getData()) {
//            datum.setStatus(3);
//            datum.setMaterialTotal(0);
//        }
//        return resVo;

    @Transactional
    public void edit(PositionEditReqVo reqVo) {
        Integer count = positionMapper.lambdaQuery()
                .ne(Position::getId, reqVo.getId())
                .eq(Position::getMyCode, reqVo.getMyCode())
                .count();
        if (count > 0) {
            throw SyExceptionUtils.e("料位编码已存在");
        }

        Position position = MkBeanUtils.copyProperties(reqVo, Position.class);
        position.setType(1);
        positionMapper.updateById(position);
    }

    @Transactional
    public void delete(BaseIdReqVo reqVo) {
        positionMapper.deleteById(reqVo.getId());
    }

    public void trayIn(PositionTrayInReqVo reqVo) {
        List<PartPallet> list = partPalletMapper.lambdaQuery().eq(PartPallet::getLoadingCode, reqVo.getTrayCode()).list();
        if(CollectionUtils.isEmpty(list)){
            PartPallet pallet=new PartPallet();
            pallet.setLoadingCode(reqVo.getTrayCode());
            pallet.setPositionCode(reqVo.getPositionCode());
            pallet.setPartCount(0);
            pallet.setType(1);
            pallet.setPartType(2);
            pallet.setPhaseSeq(0);
            partPalletMapper.insert(pallet);
        }else{
            partPalletMapper.lambdaUpdate().eq(PartPallet::getLoadingCode, reqVo.getTrayCode())
                    .set(PartPallet::getPositionCode, reqVo.getPositionCode()).update();
        }
    }

    public void trayOut(PositionTrayOutReqVo reqVo) {
        List<PartPallet> list = partPalletMapper.lambdaQuery()
                .eq(PartPallet::getLoadingCode, reqVo.getTrayCode())
                .eq(PartPallet::getPositionCode, reqVo.getPositionCode()).list();
        for (PartPallet partPallet : list){
            if(partPallet.getPartCount()>0){
               /* partPallet.setPositionCode(null);
                partPalletMapper.updateById(partPallet);*/
                partPalletMapper.lambdaUpdate().eq(PartPallet::getId,partPallet.getId())
                        .set(PartPallet::getPositionCode,null).set(PartPallet::getStationCode,null).update();
            }else{
                partPalletMapper.deleteById(partPallet.getId());
            }
        }


    }

    @Transactional
    public void partIn(PositionPartInReqVo reqVo) {
        Part part =partService.getPart(null, reqVo.getPlmId(), reqVo.getPhaseCode());
        // 添加零件的位置
        PartPallet pallet = partPalletMapper.lambdaQuery()
                .eq(PartPallet::getPlmId, reqVo.getPlmId())
                .eq(PartPallet::getPhaseCode, reqVo.getPhaseCode())
                .eq(PartPallet::getPositionCode, reqVo.getPositionCode())
                .eq(PartPallet::getType, 2)
                .one();

        if(pallet != null) {
            pallet.setPartCount(pallet.getPartCount() + reqVo.getQuantity());
            partPalletMapper.updateById(pallet);
        } else {
            pallet = new PartPallet();
            pallet.setPositionCode(reqVo.getPositionCode());
            pallet.setLoadingCode(reqVo.getPositionCode());
            pallet.setPlmId(reqVo.getPlmId());
            pallet.setPhaseCode(reqVo.getPhaseCode());
            pallet.setPartCount(reqVo.getQuantity());
            pallet.setPrePhaseCode(part.getPrePhaseCode());
            pallet.setType(2);
            pallet.setPartType(reqVo.getPartType());
            partPalletMapper.insert(pallet);
        }

    }

    @Transactional
    public void partOut(PositionPartOutReqVo reqVo) {
        PartPallet pp = partPalletMapper.lambdaQuery()
                .eq(PartPallet::getPlmId, reqVo.getPlmId())
                .eq(PartPallet::getPhaseCode, reqVo.getPhaseCode())
                .eq(PartPallet::getPositionCode, reqVo.getPositionCode())
                .eq(PartPallet::getType, 2)
                .one();

        if(pp == null){
            throw SyExceptionUtils.e("零件不在该料位上");
        }

        if(pp.getPartCount() < reqVo.getQuantity()){
            throw SyExceptionUtils.e("零件数量不足");
        }

        // 更新零件数量
        pp.setPartCount(pp.getPartCount() - reqVo.getQuantity());
        partPalletMapper.updateById(pp);

        // 如果数量为0，删除
        if(pp.getPartCount() == 0){
            partPalletMapper.deleteReal(pp.getId());
        }


    }

    public void sysPosition(PositionAddReqVo reqVo) throws IOException {
//        List<String> strings = FileUtils.readLines(new File("D:\\Users\\031392\\Desktop\\postion.txt"), "UTF-8");
//       File file=new File("D:\\Users\\031392\\Desktop\\result.txt");
//        for (String s : strings){
//            if(StringUtils.isEmpty(s)){
//                break;
//            }
//            String[] position= s.split(",");
//            Position p = positionMapper.lambdaQuery()
//                    .eq(Position::getMyCode,position[0])
//                    .one();
//            if (ObjectUtils.isEmpty(p)){
//                Station station = stationMapper.lambdaQuery()
//                        .eq(Station::getMyCode, position[2])
//                        .one();
//                if(ObjectUtils.isEmpty(station)){
//                 FileUtils.write( file,position[2]+"\r\n",true);
//                }else{
//                    Position pos = new Position();
//                    pos.setMyCode(position[0]);
//                    pos.setName(position[1]);
//                    pos.setStationId(station.getId());
//                    pos.setType(4);
//                    positionMapper.insert(pos);
//
//                }
//            }
//        }
    }

    public void assembleIn(AssembleInReqVo reqVo) {
        PartPallet pp = partPalletMapper.lambdaQuery()
                .eq(PartPallet::getUniqueCode, reqVo.getPackageNo())
                .one();
         if(ObjectUtils.isEmpty(pp)){
     //             throw SyExceptionUtils.e("{}组件未找到",reqVo.getPackageNo());
         }else{
             if(StringUtils.hasText(reqVo.getStorageLocation())){
                 pp.setPositionCode(reqVo.getStorageLocation());
                 pp.setStationCode(reqVo.getWorkPlace());
                 pp.setType(3);
                 partPalletMapper.updateById(pp);
                 if(StringUtils.hasText(reqVo.getWorkPlace())){
                     // 组件到达即开工
                     try {
                         EmbeddedStartModel start=new EmbeddedStartModel();
                         start.setUniqueCode(reqVo.getPackageNo());
                         start.setAssemblyNumber(reqVo.getPlmid());
                         start.setWorkPlaceName(reqVo.getWorkPlace());
                         start.setWorker("");
                         workshopService.startWorkByPart(start);
                     } catch (Exception e) {
                         e.printStackTrace();
//                         throw new RuntimeException(e);
                     }
                 }


             }else{
                 partPalletMapper.lambdaUpdate().eq(PartPallet::getId,pp.getId()).set(PartPallet::getLoadingCode,null)
                         .set(PartPallet::getPositionCode,null).set(PartPallet::getStationCode,null).set(PartPallet::getType,null).update();
             }


         }

    }

    public void assembleLeave(AssembleInReqVo reqVo) {
        List<PartPallet> pps = partPalletMapper.lambdaQuery()
                .eq(PartPallet::getPositionCode, reqVo.getStorageLocation())
                .list();
        for (PartPallet partPallet : pps){
            partPalletMapper.lambdaUpdate().eq(PartPallet::getId,partPallet.getId()).set(PartPallet::getLoadingCode,null)
                    .set(PartPallet::getPositionCode,null).set(PartPallet::getStationCode,null).set(PartPallet::getType,null).update();
        }

    }
}
